package com.creditease.rss.ui;

import java.io.File;
import java.io.FileOutputStream;

import android.R.bool;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.Gallery;
import android.widget.Gallery.LayoutParams;
import android.widget.ImageSwitcher;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.ViewSwitcher.ViewFactory;
import android.widget.ZoomControls;

import com.creditease.rss.RssConst;
import com.creditease.rss.util.AsyncImageLoader3;
import com.creditease.rss.util.FileUtil;
import com.creditease.rss.util.PicDownloadUtil;
import com.creditease.rss.util.ScalingUtilities;
import com.creditease.rss.util.ScalingUtilities.ScalingLogic;

public class ImageSwitcherActivity extends Activity implements ViewFactory {
    private RssImageSwitcher switcher;
    private String[] list;
    private GestureDetector detector;
    private int index = 0;
    private TextView imageTitle;
    private TextView imageIndex;
    private String rssTitle;
    private final static String TAG = ImageSwitcherActivity.class.getName();
    private AsyncImageLoader3 asyncImageLoader3 = new AsyncImageLoader3();
    private ProgressBar processbar;
    private int screenWidth;
    private int screenHeight;
    private ZoomControls zoom;
    private Bitmap bmp;
    private LinearLayout layout;
    private boolean layoutVisable = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	requestWindowFeature(Window.FEATURE_NO_TITLE);
	setContentView(R.layout.image_switch);

	WindowManager windowManager = getWindowManager();
	Display display = windowManager.getDefaultDisplay();
	screenWidth = display.getWidth();
	screenHeight = display.getHeight();

	switcher = (RssImageSwitcher) findViewById(R.id.imageSwitcher);
	layout = (LinearLayout) findViewById(R.id.image_switch_bottom_layout);
	switcher.setFactory(this);
	switcher.setInAnimation(AnimationUtils.loadAnimation(this,
		android.R.anim.fade_in));
	switcher.setOutAnimation(AnimationUtils.loadAnimation(this,
		android.R.anim.fade_out));
	// switcher.setLongClickable(true);
	processbar = (ProgressBar) findViewById(R.id.image_progressbar);
	Intent intent = getIntent();
	list = intent.getExtras().getStringArray("list");
	index = intent.getExtras().getInt("index");
	rssTitle = intent.getExtras().getString("rssTitle");
	imageTitle = (TextView) findViewById(R.id.imageTitle);
	imageIndex = (TextView) findViewById(R.id.imageIndex);
	imageTitle.setText(rssTitle);
	detector = new GestureDetector(new MySimpleGesture());

	for (int i = 0; i < list.length; i++) {
	    if (i == index) {
		continue;
	    }
	    String path = list[i];
	    if (path.startsWith("http")) {
		String newFileName = FileUtil.getFileName(path);
		// 后缀
		String filePath = RssConst.PIC_TMP_DIR + newFileName;
		PicDownloadUtil.add2Queue(path, filePath);
	    }
	}

	zoom = (ZoomControls) findViewById(R.id.zoomcontrol);
	zoom.setIsZoomInEnabled(true);
	zoom.setIsZoomOutEnabled(true);
	// zoom.hide();
	// 图片放大
	zoom.setOnZoomInClickListener(new OnClickListener() {
	    public void onClick(View v) {

		zoom.setIsZoomOutEnabled(true);
		View view = switcher.getSelectedView();
		imageView = (MyImageView) view;
		// 设置图片放大但比例
		scale = (float) (scale + 0.1);

		imageView.zoomTo(scale, HomeActivity.screenWidth / 2,
			HomeActivity.screenHeight / 2, 200f);
		if (scale >= 1.8) {
		    zoom.setIsZoomInEnabled(false);
		}
	    }
	});
	// 图片减小
	zoom.setOnZoomOutClickListener(new OnClickListener() {

	    public void onClick(View v) {

		zoom.setIsZoomInEnabled(true);

		// 设置图片放大到指定比例
		scale = (float) (scale - 0.1);
		imageView.zoomTo(scale, HomeActivity.screenWidth / 2,
			HomeActivity.screenHeight / 2, 200f);
		if (scale <= 0.4) {
		    zoom.setIsZoomOutEnabled(false);
		}
	    }

	});
	switcher.setOnTouchListener(new OnTouchListener() {

	    float baseValue;
	    float originalScale;

	    @Override
	    public boolean onTouch(View v, MotionEvent event) {
		View view = switcher.getSelectedView();
		if (view instanceof MyImageView) {
		    imageView = (MyImageView) view;

		    if (event.getAction() == MotionEvent.ACTION_DOWN) {
			baseValue = 0;
			originalScale = imageView.getScale();
		    }
		    if (event.getAction() == MotionEvent.ACTION_MOVE) {
			if (event.getPointerCount() == 2) {
			    float x = event.getX(0) - event.getX(1);
			    float y = event.getY(0) - event.getY(1);
			    float value = (float) Math.sqrt(x * x + y * y);// 计算两点的距离
			    // System.out.println("value:" + value);
			    if (baseValue == 0) {
				baseValue = value;
			    } else {
				float scale = value / baseValue;// 当前两点间的距离除以手指落下时两点间的距离就是需要缩放的比例。
				// scale the image
				imageView.zoomTo(originalScale * scale, x
					+ event.getX(1), y + event.getY(1));
			    }
			}
		    }
		}
		return false;
	    }
	});
	// 显示图片
	showImg();
	// switcher.setLongClickable(true);
    }

    private float scale = 0;

    @Override
    public View makeView() {
	MyImageView i = new MyImageView(this, screenWidth, screenHeight);
	i.setBackgroundColor(0xFF000000);
	ImageSwitcher.LayoutParams param = new ImageSwitcher.LayoutParams(
		LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT,
		Gravity.CENTER);

	i.setLayoutParams(param);
	return i;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
	this.detector.onTouchEvent(event);
	final int action = event.getAction();
	final int fingersCount = event.getPointerCount();
	if ((action == MotionEvent.ACTION_POINTER_UP) && (fingersCount == 2)) {
	    // 判断上下边界是否越界
	    View view = switcher.getSelectedView();
	    if (view instanceof MyImageView) {
		imageView = (MyImageView) view;
		float width = imageView.getScale() * imageView.getImageWidth();
		float height = imageView.getScale()
			* imageView.getImageHeight();
		if ((int) width <= HomeActivity.screenWidth
			&& (int) height <= HomeActivity.screenHeight)// 如果图片当前大小<屏幕大小，判断边界
		{

		} else {
		    float v[] = new float[9];
		    Matrix m = imageView.getImageMatrix();
		    m.getValues(v);
		    float top = v[Matrix.MTRANS_Y];
		    float bottom = top + height;
		    if (top > 0) {
			imageView.postTranslateDur(-top, 200f);
		    }
		    Log.i("manga", "bottom:" + bottom);
		    if (bottom < HomeActivity.screenHeight) {
			imageView.postTranslateDur(HomeActivity.screenHeight
				- bottom, 200f);
		    }
		    return false;
		}
	    }
	}
	return super.onTouchEvent(event);

    }

    private MyImageView imageView;

    public Bitmap getBitmap4FIT(String path, int dstWidth, int dstHeight) {
	Options options = new Options();
	options.inJustDecodeBounds = true;
	BitmapFactory.decodeFile(path, options);
	options.inJustDecodeBounds = false;

	dstWidth = options.outWidth;
	dstHeight = options.outHeight;
	// Part 1: Decode image
	Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, dstWidth,
		dstHeight, ScalingLogic.FIT);

	// Part 2: Scale image
	Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(
		unscaledBitmap, dstWidth, dstHeight, ScalingLogic.FIT);
	unscaledBitmap.recycle();

	return scaledBitmap;

    }

    public Bitmap getBitmap4CROP(String path, int dstWidth, int dstHeight) {

	// Part 1: Decode image
	Bitmap unscaledBitmap = ScalingUtilities.decodeFile(path, dstWidth,
		dstHeight, ScalingLogic.FIT);

	// Part 2: Scale image
	Bitmap scaledBitmap = ScalingUtilities.createScaledBitmap(
		unscaledBitmap, dstWidth, dstHeight, ScalingLogic.FIT);
	unscaledBitmap.recycle();

	return scaledBitmap;

    }

    //
    // public Bitmap getBitmap(String path) {
    // try {
    // // 获取源图片的大小
    // BitmapFactory.Options opts = new BitmapFactory.Options();
    // //
    // 当opts不为null时，但decodeFile返回空，不为图片分配内存，只获取图片的大小，并保存在opts的outWidth和outHeight
    // BitmapFactory.decodeFile(path, opts);
    // int srcWidth = opts.outWidth;
    // int srcHeight = opts.outHeight;
    // int destWidth = 0;
    // int destHeight = 0;
    // // 缩放的比例
    //
    // double ratio = 0.0; // tvInfo是一个TextView用于显示图片的尺寸信息 //
    // // tvInfo.setText("Width:" + srcWidth + " Height:" + srcHeight); //
    // // 按比例计算缩放后的图片大小，maxLength是长或宽允许的最大长度
    // if (srcWidth > srcHeight) {
    // ratio = srcWidth / srcWidth;
    // destWidth = srcWidth;
    // destHeight = (int) (srcHeight / ratio);
    // } else {
    // ratio = srcHeight / srcHeight;
    // destHeight = srcHeight;
    // destWidth = (int) (srcWidth / ratio);
    // }
    // // 对图片进行压缩，是在读取的过程中进行压缩，而不是把图片读进了内存再进行压缩
    // BitmapFactory.Options newOpts = new BitmapFactory.Options();
    // // 缩放的比例，缩放是很难按准备的比例进行缩放的，目前我只发现只能通过inSampleSize来进行缩放，
    // // 其值表明缩放的倍数，SDK中建议其值是2的指数值
    // newOpts.inSampleSize = (int) ratio + 1;
    // // inJustDecodeBounds设为false表示把图片读进内存中
    // newOpts.inJustDecodeBounds = false;
    // // 设置大小，这个一般是不准确的，是以inSampleSize的为准，但是如果不设置却不能缩放
    // newOpts.outHeight = destHeight;
    // newOpts.outWidth = destWidth;
    // // 获取缩放后图片
    // Bitmap destBm = BitmapFactory.decodeFile(path, newOpts);
    // return destBm;
    //
    // } catch (Exception e) {
    // }
    // return null;
    // }

    private void showImg() {
	Log.d(TAG, "index=" + index + ",count=" + list.length);
	final String path = list[index];
	Log.d(TAG, path);
	imageIndex.setText((index + 1) + "/" + list.length);
	if (!path.startsWith("http")) {
	    bmp = getBitmapLocal(path);
	} else {

	    String newFileName = FileUtil.getFileName(path);
	    // 后缀
	    final String filePath = RssConst.PIC_TMP_DIR + newFileName;
	    File file = new File(filePath);
	    if (file.exists()) {
		bmp = getBitmapLocal(filePath);
	    } else {
		processbar.setVisibility(View.VISIBLE);
		asyncImageLoader3.loadDrawable(path,
			new AsyncImageLoader3.ImageCallback() {
			    public void imageLoaded(Drawable imageDrawable) {
				// is.setImageDrawable(imageDrawable);
				if (imageDrawable != null) {
				    // 保存图片
				    try {

					BitmapDrawable bd = (BitmapDrawable) imageDrawable;
					bmp = bd.getBitmap();
					FileOutputStream fos = new FileOutputStream(
						filePath);
					bmp.compress(
						Bitmap.CompressFormat.JPEG,
						100, fos);
					fos.flush();
					fos.close();
					bmp = getBitmapLocal(filePath);
					processbar.setVisibility(View.GONE);
				    } catch (Exception e) {
					e.printStackTrace();
				    }
				} else {
				    Log.d(TAG, "index=============");
				}
			    }
			});
	    }
	}
    }

    private Bitmap getBitmapLocal(String path) {
	Bitmap bitmap = getBitmap4FIT(path, screenWidth, screenHeight);
	switcher.setImageDrawable(bitmap, bitmap.getWidth(), bitmap.getHeight());
	View view = switcher.getSelectedView();
	Log.d(TAG, "bitmap.getWidth()=" + bitmap.getWidth()
		+ ",bitmap.getHeight()=" + bitmap.getHeight());
	imageView = (MyImageView) view;
	Log.d(TAG, "scale=" + scale + "    " + imageView.getScale());
	scale = imageView.getScale();
	imageView.zoomTo(imageView.getScaleRate(),
		HomeActivity.screenWidth / 2, HomeActivity.screenHeight / 2,
		100f);

	return bitmap;
    }

    private class MySimpleGesture extends SimpleOnGestureListener {
	// 按两下的第二下Touch down时触发
	public boolean onDoubleTap(MotionEvent e) {
	    View view = switcher.getSelectedView();
	    if (view instanceof MyImageView) {
		imageView = (MyImageView) view;
		if (imageView.getScale() > imageView.getScaleRate()) {
		    imageView.zoomTo(imageView.getScaleRate(),
			    HomeActivity.screenWidth / 2,
			    HomeActivity.screenHeight / 2, 200f);
		} else {
		    imageView.zoomTo(1.5f, HomeActivity.screenWidth / 2,
			    HomeActivity.screenHeight / 2, 200f);
		}

	    } else {

	    }
	    return true;
	}

	float baseValue = 0;

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
		float velocityY) {
	    if (e1.getX() - e2.getX() > 120) {
		// 如果到达最大页
		if ((index + 1) == list.length) {
		    index = -1;
		}
		index++;
		showImg();
		zoom.setIsZoomInEnabled(true);
		zoom.setIsZoomOutEnabled(true);
		return true;
	    }
	    if (e2.getX() - e1.getX() > 120) {
		if (index == 0) {
		    index = list.length;
		}
		index--;
		showImg();
		zoom.setIsZoomInEnabled(true);
		zoom.setIsZoomOutEnabled(true);

		return true;
	    }
	    float y = e2.getY() - e1.getY();
	    //向下滑动
	    if (y > 50) {
		float scale2 = y / screenHeight;// 当前两点间的距离除以手指落下时两点间的距离就是需要缩放的比例。
		// scale the image
		imageView.zoomTo(scale + scale2, e1.getX(), e1.getY());
		return true;
	    }
	    //向上滑动
	    if (y < 0) {
		float z = Math.abs(y);
		if (z > 50) {
		    float scale2 = z / screenHeight;// 当前两点间的距离除以手指落下时两点间的距离就是需要缩放的比例。
		    // scale the image
		    imageView.zoomTo(scale - scale2, e1.getX(), e1.getY());
		    return true;
		}
	    }

	    return false;
	}

	@Override
	public boolean onScroll(MotionEvent e1, MotionEvent e2,
		float distanceX, float distanceY) {
	    View view = switcher.getSelectedView();
	    if (view instanceof MyImageView) {
		imageView = (MyImageView) view;

		float v[] = new float[9];
		Matrix m = imageView.getImageMatrix();
		m.getValues(v);
		// 图片实时的上下左右坐标
		float left, right; // 图片的实时宽，高
		float width, height;
		width = imageView.getScale() * imageView.getImageWidth();
		height = imageView.getScale() * imageView.getImageHeight();
		// 一下逻辑为移动图片和滑动gallery换屏的逻辑。如果没对整个框架了解的非常清晰，改动以下的代码前请三思！！！！！！
		if ((int) width <= HomeActivity.screenWidth
			&& (int) height <= HomeActivity.screenHeight)
		// 如果图片当前大小<屏幕大小，直接处理滑屏事件
		{
		    return super.onScroll(e1, e2, distanceX, distanceY);
		} else {
		    left = v[Matrix.MTRANS_X];
		    right = left + width;
		    Rect r = new Rect();
		    imageView.getGlobalVisibleRect(r);

		    if (distanceX > 0)
		    // 向左滑动
		    {
			if (r.left > 0) {
			} else if (right < HomeActivity.screenWidth) { // 如果到达最大页

			} else {
			    imageView.postTranslate(-distanceX, -distanceY);
			    return true;
			}
		    } else if (distanceX < 0)// 向右滑动
		    {
			if (r.right < HomeActivity.screenWidth) {

			} else if (left > 0) {
			} else {
			    imageView.postTranslate(-distanceX, -distanceY);
			    return true;
			}
		    }
		}
	    } else {
		return super.onScroll(e1, e2, distanceX, distanceY);
	    }
	    return false;
	}

	@Override
	public void onLongPress(MotionEvent e) {
	    if (layoutVisable) {
		layout.setVisibility(View.GONE);
		layoutVisable = false;
	    } else {
		layout.setVisibility(View.VISIBLE);
		layoutVisable = true;
	    }
	    super.onLongPress(e);
	}

    }

}
